package com.k.kc.util;

import com.k.kc.util.base64.Base64;

import java.util.Arrays;

/**
 * String part1 = base64UrlEncode(header)
 * String part2 = base64UrlEncode(payload)
 * String part3 = base64UrlEncode(
 *  HMACSHA256(
 *  part1 + "." +
 *  part2,
 *  secret)
 *  )
 *  String jws = part1 +"."+part2+"."+part3
 *  https://datatracker.ietf.org/doc/html/rfc4648#section-5
 *  BASE64URL is an RFC 4648 Base64URL decoder
 *
 * @author k
 */
public class JwtUtils {
    public static void main(String[] args) {
        String headerJson = "{\"alg\":\"HS256\",\"typ\":\"JWT\"}";
        String claimsJson = "{\"sub\":\"12啊3456气味儿童789看0\",\"name\":\"Tom猫个的12\"}";
        byte[] bytes2 = new byte[]{
                49, 50, 51, 52,
                53, 54, 55, 56,
                57, 48, 49, 50,
                51, 52, 53, 54,
                55, 56, 57, 48,
                49, 50, 51, 52,
                53, 54, 55, 56,
                57, 48, 49, 50
        };
        try {
            System.out.println("256 位 key:"+Arrays.toString(bytes2));
            System.out.println("header:" + headerJson);
            System.out.println("payload:" + claimsJson);
            String jwt = genJwt(headerJson,claimsJson,bytes2);
            // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMuWVijM0NTbmsJTlkbPlhL_nq6U3ODnnnIswIiwibmFtZSI6IlRvbeeMq-S4queahDEyIn0.g2XZioFF2uVzrXrFQgo7GnjGUzO9MR-nDWMyWC-4X0I
            System.out.println("jwt:" + jwt);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static String genJwt(String headerJson,String payloadJson,byte[] secret256) throws Exception {
        String part1 = Base64.encodeBase64URLSafeString(headerJson.getBytes("UTF-8"));
        String part2 = Base64.encodeBase64URLSafeString(payloadJson.getBytes("utf-8"));

        byte[] signature = HashKit.HmacSHA256((part1+"."+part2).getBytes("utf-8"),secret256);
        String part3 = Base64.encodeBase64URLSafeString(signature);
        String jwt = part1 + "." + part2 +"." + part3;
        return jwt;

    }
}
